#!/usr/bin/env bash

# PACKAGE: Gunther
# VERSION: 2.0
# DATE: 12/09/08
# AUTHOR(S): Zarrar Shehzad

# Checks a 1D file

# INCLUDE
source "$GUNTHERDIR/include/Asourceall.sh"

# VARIABLES
commandFile="${GUNTHERDIR}/commands/checkTs.sh" # can override this file at command-line
tsFile=""
checkVols=1
checkMin=1
to_trash=0

# USAGE
function usage {
    changegood green
    echo
    echo "Usage"
    echo "  $0 -i <time series file> -v <expected number of volumes for time series>"
    echo "Program:"
    echo "   Check mean time series in 1D file"
    echo "Required Options:"
    echo "  * -i"
    echo "Available Options:"
    echo "  -i: time series file"
    echo "  -v: number of expected time points (default: ${gVOLNUM})"
    echo "  -d: delete file with error"
    echo "  -t: only checks that the number of time points is correct"
    echo "  -m: only checks that the minimum time point is not 0"
    echo
    changebad
}

if [[ "$#" = 0 ]]; then
    usage
    exit 2
fi

# PARSE OPTIONS
while getopts ":i:v:dtm" Option; do    
    case $Option in
        i ) tsFile="$OPTARG"
            if [[ ! -e "$tsFile" ]]; then
                zerror "Cannot find time series file '${tsFile}'!"
                exit -1
            fi
            ;;
        v ) gVOLNUM="$OPTARG"
            ;;
        d ) to_trash=1
            ;;
        t ) checkVols=1
            checkMin=0
            ;;
        m ) checkMin=1
            checkVols=0
            ;;
    	: ) zerror "Argument value required for option '-$OPTARG'"
    	    exit -1
    	    ;;
    	? ) zerror "Unimplemented option '-$OPTARG' chosen"
    	    exit -1
    	    ;;
    	* ) zerror "Unknown error while processing options...continuing anyway"
    	    ;;
    esac
done

## save command
command="$@"
## move past any options
shift $((${OPTIND}-1))

# Check on required input
if [[ -z "$tsFile" ]]; then
    zerror "Please specify time series file (-i)"
    exit -2
fi

## Get/check number of time points
if [[ "$checkVols" ]]; then
    tsVols=$(( `awk 'NF > 0' ${tsFile} | wc -l` ))
    if [[ "$tsVols" -ne "$gVOLNUM" ]]; then
        zerror "...checking number of time points...expected to find (${gVOLNUM}) isntead found (${tsVols})"
        if [[ "$to_trash" = 1 ]]; then
            zcmd "rm ${tsFile}"
        fi
        # remove file
        exit -3
    else
        zinfo "...checking number of time points...value is '${tsVols}'"
    fi
fi

## Get/check minimum time point
if [[ "$checkMin" ]]; then
    minTs=$( echo `3dTstat -prefix - -min ${tsFile}\' 2> /dev/null` )
    if [[ "$minTs" = 0 ]]; then
        zerror "...checking minimum time point...error at least one time point was 0, something must be wrong"
        if [[ "$to_trash" = 1 ]]; then
            zcmd "rm ${tsFile}"
        fi
        exit -3
    else
        zinfo "...checking minimum time point...value is '${minTs}'"
    fi
fi

